import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { Icon, Radio, TimePicker, Tooltip, Select } from 'antd';
import { withRouter } from 'react-router';

import {
  descriptions,
  detectionMinTime
} from '@containers/asset-manage/components/detection-task-modal/constants';
import { TASK_PRIORITY_MAP } from '@util/constants';
import TaskLimitDate from '@components/task-limit-date';
import checkDetectionTime from '@util/checkDetectionTime';
import { connect } from 'react-redux';
import OnedayDetectionIgnore from '../oneday-detection-ignore';
import './index.less';
import _ from 'lodash';
const scanList = [{ label: '自动分发', value: 'auto' }];
const TaskCommonFields = props => {
  const { onCommonFieldChange, prefixCls, history, isCluster } = props;
  const [timing, setTiming] = useState({ dailyStart: '', dailyEnd: '' });
  const [startAt, setStartAt] = useState();
  const [endAt, setEndAt] = useState();
  const [priority, setPriority] = useState('middle');
  const [ignoreType, setIgnoreType] = useState({
    whitelist: true,
    custom: false
  });
  const [errorMsgMap, setErrorMsgMap] = useState({
    timeRange: '',
    detectionTime: ''
  });
  const [scanNodes] = useState('auto');
  // 网口变量
  const [setInterfaces] = useState();
  // 网口下拉列表
  // const [interfacesList] = useState([]);

  const checkTime = () => {
    if (errorMsgMap.timeRange) {
      return;
    }

    const hasDetectEnoughTime = checkDetectionTime({ timing, startAt, endAt });
    setErrorMsgMap({
      ...errorMsgMap,
      detectionTime: hasDetectEnoughTime ? '' : '运行时间小于30分钟，请重新选择'
    });
  };

  const handleIgnoreTypeChange = e => {
    const value = e.target.value;
    const checked = e.target.checked;
    setIgnoreType({ ...ignoreType, [value]: checked });
  };

  const handleJumpWhitelist = () => {
    history.push('/asset-config/white-list');
  };

  const onTimeRangeChange = (key, time) => {
    let { dailyStart, dailyEnd } = timing;
    let timeRangeError = '';
    if (key === 'dailyStart') {
      dailyStart = time;
    } else {
      dailyEnd = time;
    }
    if (!dailyEnd) {
      timeRangeError = '请选择终止时间';
    }
    if (!dailyStart) {
      timeRangeError = '请选择起始时间';
    }

    if (dailyStart && dailyEnd) {
      const gap = dailyEnd - dailyStart;

      if (gap < detectionMinTime && gap > -detectionMinTime) {
        timeRangeError = '终止时间要大于起始时间30分钟以上';
      }
    }

    if (!dailyStart && !dailyEnd) {
      timeRangeError = '';
    }

    setTiming({ ...timing, dailyStart, dailyEnd });
    setErrorMsgMap({
      ...errorMsgMap,
      timeRange: timeRangeError
    });
  };

  const onDateStartChange = startAt => {
    setStartAt(startAt);
  };

  const onDateEndChange = endAt => {
    setEndAt(endAt);
  };

  useEffect(() => {
    checkTime();
  }, [startAt, endAt, timing]);

  useEffect(() => {
    const errorMsg = Object.values(errorMsgMap).filter(Boolean)[0] || '';
    onCommonFieldChange({
      startAt,
      endAt,
      timing,
      errorMsg,
      priority,
      ignoreType,
      scanNodes
    });
  }, [startAt, endAt, timing, errorMsgMap, priority, ignoreType, scanNodes]);

  const timeError = errorMsgMap.timeRange || errorMsgMap.detectionTime;
  return (
    <>
      <div className={`${prefixCls}-item`}>
        <span className={`${prefixCls}-item-sub-title`}>
          定时设置
          <Tooltip title={descriptions.dateLimit}>
            <Icon type="exclamation-circle" />
          </Tooltip>
        </span>
        <TaskLimitDate onDateStartChange={onDateStartChange} onDateEndChange={onDateEndChange} />
      </div>
      <div className={`${prefixCls}-item`}>
        <span className={`${prefixCls}-item-sub-title`}>
          每日允许时间段
          <Tooltip title={descriptions.timeLimit}>
            <Icon type="exclamation-circle" />
          </Tooltip>
        </span>
        <div className="time-picker-range">
          <TimePicker
            className="daily-start"
            placeholder="开始时间"
            format="HH:mm"
            value={timing.dailyStart}
            onChange={time => onTimeRangeChange('dailyStart', time)}
          />
          &nbsp;&nbsp;
          <TimePicker
            className="daily-end"
            placeholder="结束时间"
            format="HH:mm"
            value={timing.dailyEnd}
            onChange={time => onTimeRangeChange('dailyEnd', time)}
          />
        </div>
      </div>
      {timeError && <p className="validate-error time-range-error">{timeError}</p>}
      {isCluster && (
        <div className={`${prefixCls}-item`} style={{ marginBottom: 0 }}>
          <span className={`${prefixCls}-item-sub-title`}>扫描节点</span>
          <Select
            onChange={e => setInterfaces(e)}
            value={scanNodes}
            getPopupContainer={triggerNode => triggerNode.parentNode}
            style={{ width: 200 }}
          >
            {scanList.map(item => {
              return (
                <Select.Option value={item.value} key={item.value}>
                  {item.label}
                </Select.Option>
              );
            })}
          </Select>
        </div>
      )}

      <div className={`${prefixCls}-item`} style={{ marginTop: 24 }}>
        <span className={`${prefixCls}-item-sub-title`}>优先级</span>
        <Radio.Group
          className="priority-group"
          value={priority}
          onChange={e => setPriority(e.target.value)}
        >
          {Object.keys(TASK_PRIORITY_MAP).map(key => (
            <Radio key={key} value={key}>
              {TASK_PRIORITY_MAP[key]}
            </Radio>
          ))}
        </Radio.Group>
      </div>

      <OnedayDetectionIgnore
        handleIgnoreTypeChange={handleIgnoreTypeChange}
        prefixCls={prefixCls}
        handleJumpWhitelist={handleJumpWhitelist}
      />
    </>
  );
};

TaskCommonFields.propTypes = {
  history: PropTypes.object,
  prefixCls: PropTypes.string,
  onCommonFieldChange: PropTypes.func,
  isCluster: PropTypes.boolean
};

const mapStateToProps = state => {
  return {
    isCluster: _.get(state, 'auth.cert.is_cluster', false)
  };
};

export default withRouter(connect(mapStateToProps)(TaskCommonFields));
